package cn.edu.zafu.bigdata.zyf;

public class ArrayIndexOutOfBoundsExceptionHandling {

    // 方法getElement，当索引超出范围时抛出ArrayIndexOutOfBoundsException
    public static int getElement(int[] arr, int index) {
        if (index < 0 || index >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + arr.length);
        }
        return arr[index];
    }

    public static void main(String[] args) {
        int[] array = {10, 20, 30, 40, 50};
        int index = 5; // 越界的索引

        try {
            // 尝试调用getElement方法
            int element = getElement(array, index);
            System.out.println("The element at index " + index + " is: " + element);
        } catch (ArrayIndexOutOfBoundsException e) {
            // 捕获异常并输出提示信息
            System.out.println("Error: " + e.getMessage());
        }
    }
}